<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="loadForm" class="demo-form-inline">

      <el-form-item label="昵称">
        <el-input v-model="loadForm.nickname" size="small" clearable placeholder="昵称" @clear="listPageData" @keyup.enter.native="listPageData" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="loadForm.email" size="small" clearable placeholder="邮箱" @clear="listPageData" @keyup.enter.native="listPageData" />
      </el-form-item>
      <el-form-item label="组织名称">
        <el-select
          v-model="loadForm.organizationId"
          placeholder="组织名称"
          size="small"
          filterable
          clearable
          @visible-change="listUserOrganizationInfo"
          @clear="listPageData"
        >
          <el-option
            v-for="item in organizationList"
            :key="item.id"
            :label="item.organizationName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" type="primary" size="mini" @click="listData">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      highlight-current-row
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column label="账号" prop="username" align="center" />
      <el-table-column label="昵称" prop="nickname" align="center" />
      <el-table-column label="邮箱" prop="email" align="center" />
      <el-table-column label="组织名称" prop="organizationName" align="center" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" :disabled="dealHandUpdateOrDelete(scope.row)" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :disabled="dealHandUpdateOrDelete(scope.row)" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="loadForm.pageNum"
      :limit.sync="loadForm.pageSize"
      @pagination="listPageData"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" clearable label-width="80px">

        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" clearable placeholder="请输入账号" />
        </el-form-item>

        <el-form-item v-if="showInputPassword()" label="密码" prop="password">
          <el-input v-model="form.password" clearable show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-if="showInputPassword()" label="确认密码" prop="password">
          <el-input v-model="form.rePassword" clearable show-password placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" clearable placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
        </el-form-item>

        <el-form-item label="组织" prop="organizationId">
          <el-select v-model="form.organizationId" placeholder="请选择组织" filterable clearable style="width: 380px;">
            <el-option
              v-for="item in organizationList"
              :key="item.id"
              :label="item.organizationName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { load, findOrganization, add, update, downExcel } from '@/api/user/user.js'
import { getDetail, remove } from '@/api/system/common-back.js'
export default {
  name: 'User',
  // 加载分页组件
  components: { Pagination },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 默认当前页
      currentPage: 1,
      // 总页数
      totalCount: 0,
      // 导出遮罩层
      exportLoading: false,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 弹出层标题
      title: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // id集合
      ids: [],
      // 查询条件
      loadForm: {
        pageNum: 1,
        pageSize: 10,
        // 具体查询条件
        nickname: undefined,
        email: undefined,
        organizationId: undefined
      },
      // 通用详情/删除条件
      commonForm: {
        id: undefined,
        idList: [],
        tableName: 'user'
      },
      // 组织下拉框
      organizationList: []
    }
  },

  // 钩子函数
  created() {
    this.listPageData()
  },
  methods: {
    // 查询页面数据
    listPageData() {
      console.log('加载数据')
      load(this.loadForm).then(response => {
        this.tableData = response.data.records
        this.totalCount = response.data.total
      })
    },

    // 查询组织下拉列表
    listUserOrganizationInfo() {
      findOrganization().then(res => {
        this.organizationList = res.data
      })
    },

    // 查询按钮操作
    listData() {
      this.listPageData()
    },

    // 重置按钮操作
    resetQuery() {
      this.resetForm()
      this.listData()
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 新增修改表单重置
    reset() {
      this.form = {}
    },

    // 重置查询表单
    resetForm() {
      this.loadForm = {}
    },

    // 是否显示密码输入框
    showInputPassword() {
      if (this.title === '添加') {
        return true
      } else {
        return false
      }
    },

    // 表格多选操作
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)

      // 单选状态 值为true 可操作表单上方修改按钮
      // this.single = selection.length !== 1 && this.ids[0] !== 1
      if (selection.length !== 1) {
        const id = this.ids[0]
        console.log('id =====', this.ids)
        if (id !== 1) {
          this.single = true
        } else {
          this.single = false
        }
      }

      // 选中数据后可放开删除按钮
      this.multiple = !selection.length
    },

    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
      this.listUserOrganizationInfo()
    },

    // 删除按钮操作
    handleDelete(row) {
      const id = row.id || this.ids
      console.log('id 集合', id)

      // 处理ID集合
      if (row.id) {
        this.commonForm.idList = [id]
      } else {
        this.commonForm.idList = id
      }

      this.$modal.confirm('是否确认删除？')
        .then(() => {
          console.log('删除')
          remove(this.commonForm).then(res => {
            this.$modal.msgSuccess('操作成功')
            this.listData()
          })
        })
    },

    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      this.commonForm.id = id
      // 获取详情
      getDetail(this.commonForm).then(res => {
        this.form = res.data
        this.open = true
        this.title = '修改'
        this.listUserOrganizationInfo()
      })
    },

    // 处理单个修改或删除 管理员不做处理
    dealHandUpdateOrDelete(row) {
      const id = row.id || this.ids[0]
      if (id === 1) {
        return true
      } else {
        return false
      }
    },

    // 提交按钮
    submitForm: function() {
      if (this.form.id === undefined) {
        console.log('新增')
        this.checkSaveData()
        add(this.form).then((response) => {
          this.$modal.msgSuccess('操作成功')
          console.log('后续处理')
          this.open = false
          this.listData()
          this.reset()
        })
      } else {
        console.log('修改')
        update(this.form).then((response) => {
          this.$modal.msgSuccess('操作成功')
          console.log('后续处理')
          this.open = false
          this.listData()
          this.reset()
        })
      }
    },

    // 校验保存数据
    checkSaveData() {
      console.log('校验保存数据')
      if (this.form.password == null) {
        this.$modal.msgError('请输入密码')
        throw new Error('Some error occurred!')
      } else if (this.form.password !== this.form.rePassword) {
        this.$modal.msgError('两次输入密码不一致')
        throw new Error('Some error occurred!')
      }
    },

    // 导出excel
    handleExport() {
      this.loadForm.idList = this.ids
      console.log('导出操作 ids', this.loadForm.idList)
      this.$modal.confirm('是否确认导出数据项？')
        .then(() => {
          // console.log('导出操作函数')
          this.exportLoading = true
          downExcel(this.loadForm)
            .then(response => {
              // 获取响应头中的文件名
              const fileName = decodeURIComponent(response.headers['content-disposition'].split('=')[1])
              // 创建URL对象并指定blob数据
              const url = window.URL.createObjectURL(new Blob([response.data]))
              // 创建a标签并设置下载属性
              const link = document.createElement('a')
              link.href = url
              // 设置下载文件名
              link.setAttribute('download', fileName)
              // 添加到页面中并触发点击事件进行下载
              document.body.appendChild(link)
              link.click()
              // 下载完成后移除a标签并释放URL对象
              document.body.removeChild(link)
              window.URL.revokeObjectURL(url)
              this.exportLoading = false
              this.listPageData()
            })
            .catch(error => {
              console.error('下载Excel失败: ', error)
            })
        })
    }

  }
}
</script>

  <style>

  </style>
